package com.vue.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vue.demo.domain.User;
import com.vue.demo.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author business
 * @since 2023-03-19
 */
@Api(tags = "用户")
@RestController
@RequestMapping("/user")
public class UserController {

    private final String Key = "user";
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("getUser")
    public List<User> getUser() {

        List<User> userList=redisTemplate.opsForList().range(Key, 0, -1);
        if (!userList.isEmpty()) {
            return userList;
        }
        return userService.getUser();
    }

    @PostMapping("saveUser")
    public List<User> saveUser(@RequestBody User user) {
        //先判断redis中当前key是否存在内容，存在的话清除所有
        if (redisTemplate.opsForList().size(Key)>0){
            redisTemplate.delete(Key);
        }
        List<User> userList = new ArrayList<>();
        if (userService.save(user)) {
            List<User> list = userService.list();
            if (!list.isEmpty()) {
                redisTemplate.opsForList().rightPushAll(Key, list);
            }
        }
        userList = redisTemplate.opsForList().range(Key, 0, -1);
        return userList;
    }

}

